package com.example.eci_quartz.cloudcc.impl;

import com.example.eci_quartz.cloudcc.commcon.CommonMethod;
import com.example.eci_quartz.cloudcc.commcon.DataGroupUtil;
import com.example.eci_quartz.cloudcc.commcon.DateUtil;
import com.example.eci_quartz.cloudcc.dao.DefaultConnectionFactory;
import com.example.eci_quartz.cloudcc.dao.baseDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *同步设备信息下PIP&PSP
 */
public class NewPipPspImpl3 extends baseDao {

	SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat sdfY= new SimpleDateFormat("yyyy");
	SimpleDateFormat sdfM= new SimpleDateFormat("MMdd");
	static String binding = InsertXMInfo();
	@SuppressWarnings({ "rawtypes","unchecked" })
	public static String upsertPipPsp(){
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Map> updatelist =null;
		List<Map> insertlist =null;
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Calendar cal=Calendar.getInstance();
	    cal.set(Calendar.DATE,cal.get(Calendar.DATE)-400);
	    String firstDay=format.format(cal.getTime());

          //获取系统当天时间
	    Calendar cal2=Calendar.getInstance();
	    cal2.set(Calendar.DATE,cal2.get(Calendar.DATE)-201);
	    String newDate=format.format(cal2.getTime());

		String info = "false";
		String orderinfo = "";//查询返回来的值
		String order_datas = "";//查询成功返回来的数据
		Map<String, Map> orderMap =null;
		Map<String,Map> rsMap=null;
		String sql="select *  FROM LIBJ49FSMS.PIPPSPOLD "
		    +" WHERE DTISS8 BETWEEN '"+firstDay+"' AND '"+newDate+"'";
		int count=1;
		try {

			conn = new DefaultConnectionFactory().getConnection();
			if(conn!=null){
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
			}
			orderMap = new HashMap<String, Map>();// map<销售订单编号，销售订单对象值>
			rsMap=new HashMap<String,Map>();//map<零件号，零件数据>从DBS查询出来的
			String codes="";//项目编号数组
			String sns="";//设备数组
			if (rs != null) {
				while (rs.next()) {
					Map mapObj=new HashMap();
					//设备序列号
					String sn=(rs.getString("EQMFSN") == null ? "" : rs.getString("EQMFSN")+ "").trim();
					mapObj.put("sn", sn);
					//项目编号
					String PIPNO=(rs.getString("PIPNO") == null ? "" : rs.getString("PIPNO")+ "").trim();
					//PiP小时数
					String PPHRS=(rs.getString("PPHRS") == null ? "" : rs.getString("PPHRS")+ "").trim();
					mapObj.put("PPHRS", PPHRS);
					mapObj.put("sfjktb", 2);
					//描述
					mapObj.put("description",(rs.getString("DESC40") == null ? "" : rs.getString("DESC40")+ "").trim());
					//发布日期
			        mapObj.put("letterdate",DateUtil.getDatetoStringUtil((rs.getString("DTISS8") == null ? "" : rs.getString("DTISS8")+ "").trim()));
					//截止日期
					 mapObj.put("termdate",DateUtil.getDatetoStringUtil((rs.getString("ENDD8") == null ? "" : rs.getString("ENDD8")+ "").trim()));

					String code="";
					if((sn!=null&&!"".equals(sn))&& (PIPNO!=null&& !"".equals(PIPNO))){
							code=PIPNO+"-"+sn;
							mapObj.put("name",code);
							mapObj.put("xmbm",PIPNO);//项目编码
							//项目编号数组
							codes+="'"+code+"',";
							//设备数组
							sns+="'"+sn+"',";
						   rsMap.put(code, mapObj);
				    }
			}
			 //判断是否存在
		     if(codes!=null&&!"".equals(codes)){
					//查询系统中全部的标准工时
					String data_query = "serviceName=cqlQuery&objectApiName=pippsp" +
							"&expressions=select l.id,l.name from pippsp l " +
							"where l.name is not null and l.name in ("+codes.substring(0, codes.length()-1)+")  " +
									"and l.is_deleted='0'&binding=";//查询设备信息
					orderinfo = operate(data_query+ binding);
					JSONObject fromObject =null;
					 String result="";
					if(CommonMethod.isJSONValid(orderinfo)){
						fromObject = JSONObject.fromObject(orderinfo);
						result= fromObject.getString("result")==null?"":fromObject.getString("result");
					}
					//判断binding是否失效，如果失效，就重新获取
					if(!"true".equals(result)){
						binding=CommonMethod.getBingAgain();
						for (int i = 0; i <5; i++) {
							orderinfo=operate(data_query+binding);

							if(CommonMethod.isJSONValid(orderinfo)){
								fromObject = JSONObject.fromObject(orderinfo);
								result= fromObject.getString("result")==null?"":fromObject.getString("result");
							}
							if("true".equals(result)){
								break;
							}
						}
					}
					String returninfo = "[" + orderinfo + "]";// 手动转换成json格式，方便取值
					if (!"[]".equals(returninfo)&&orderinfo!=null) {
						JSONArray brand_list = JSONArray.fromObject(returninfo);
						if (brand_list != null) {
							for (int j = 0; j < brand_list.size(); j++) {
								JSONObject brandInfo = (JSONObject) brand_list.get(j);
								String Result = brandInfo.get("result") == null ? ""
										: brandInfo.get("result") + "";// 获取返回值
								String date = brandInfo.get("data") == null ? ""
										: brandInfo.get("data") + "";// 获取返回值
								if ("true".equals(Result)) {
									order_datas = date;
								}
							}
						}
					}
					// 查询CRM系统中PIP&PSP的信息并存入到map中
					if (order_datas != "[]"&&!"".equals(order_datas)) {
						JSONArray datas_list = JSONArray.fromObject(order_datas);
						if (datas_list != null) {
							for (int i = 0; i < datas_list.size(); i++) {
								JSONObject accObj = (JSONObject) datas_list.get(i);
								JSONObject order_newObj = new JSONObject();//新的json，只存id，编号
								//设备编号
							    String code= (accObj.get("name")==null? "" : accObj.get("name").toString()).trim();
							    if(code!=null&&!"".equals(code)){
							    	order_newObj.put("id", accObj.get("id"));
									order_newObj.put("name", code);
									orderMap.put(code,order_newObj);
							    }
							}
						}
					}
			  }
			//判断零件是新增还是更新
		     if(rsMap!=null&&rsMap.size()>0){
				;
				updatelist = new ArrayList<Map>();
				insertlist = new ArrayList<Map>();
				Map  sbMaps=EquipmentImpl.getsbglMap(sns);	//查询设备集合
			   for(String code:rsMap.keySet()){
				    Map ljObj=rsMap.get(code);//获取DBS中的客户数据
				   if(orderMap!=null){
					   if (orderMap.containsKey(code)) {// 更新设备信息
						   Map pipMap =orderMap.get(code);
						   Map  sbMap=(Map) sbMaps.get(ljObj.get("sn"));
						   if(sbMap!=null&&!"".equals(sbMap)) {
							   ljObj.put("sn", (sbMap.get("id") == null ? "" : sbMap.get("id")+ "").trim());
						   }
						  ljObj.put("id",pipMap.get("id"));
						  updatelist.add(ljObj);
						} else {// 新建设备信息
							 Map  sbMap=(Map) sbMaps.get(ljObj.get("sn"));
							 if(sbMap!=null&&!"".equals(sbMap)) {
								   ljObj.put("sn", (sbMap.get("id") == null ? "" : sbMap.get("id")+ "").trim());
							 }
							insertlist.add(ljObj);
						 }
					 }
				}
			}

			//插入新的pippsp
			if (insertlist!=null&&insertlist.size()>0) {
				Map<Integer,List> map = DataGroupUtil.dataGroup(insertlist); //用map存起来新的分组后数据,每100条一组
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayInsert = JSONArray.fromObject(amList);
						String jsonstr=jsonArrayInsert.toString();
						jsonstr = java.net.URLEncoder.encode(jsonstr, "UTF-8");
						String data_insert = "serviceName=insert&objectApiName=pippsp&data="+jsonstr+"&binding=";//insertLt批量插入，不走触发器
			            String insertInfo=operate(data_insert+ binding);//执行CRM系统插入操作insert

						//判断binding是否失效，如果失效，就重新获取
						JSONObject fromObject =null;
						 String result="";
						if(CommonMethod.isJSONValid(orderinfo)){
							fromObject = JSONObject.fromObject(orderinfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							binding=CommonMethod.getBingAgain();
							for (int i = 0; i <5; i++) {
								insertInfo=operate(data_insert+binding);

								if(CommonMethod.isJSONValid(insertInfo)){
									fromObject = JSONObject.fromObject(insertInfo);
									result= fromObject.getString("result")==null?"":fromObject.getString("result");
								}
								if("true".equals(result)){
									break;
								}
							}
						}
					    info="insert_success";
					}
				}
			}
			//更新系统中的设备信息
			if (updatelist!=null&&updatelist.size() > 0) {
				Map<Integer,List> map = DataGroupUtil.dataGroup(updatelist);
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayUpdate = JSONArray.fromObject(amList);
						String jsonstr_update=jsonArrayUpdate.toString();
						jsonstr_update = java.net.URLEncoder.encode(jsonstr_update, "UTF-8");
						String data_update = "serviceName=updateLt&objectApiName=pippsp&data="+jsonstr_update+"&binding=";//updateLt批量更新，不走触发器
			            String updateInfo=operate(data_update+binding);//执行CRM更新操作update

						//判断binding是否失效，如果失效，就重新获取
						JSONObject fromObject =null;
						 String result="";
						if(CommonMethod.isJSONValid(orderinfo)){
							fromObject = JSONObject.fromObject(orderinfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							binding=CommonMethod.getBingAgain();
							for (int i = 0; i <5; i++) {
								updateInfo=operate(data_update+binding);
								if(CommonMethod.isJSONValid(updateInfo)){
									fromObject = JSONObject.fromObject(updateInfo);
									result= fromObject.getString("result")==null?"":fromObject.getString("result");
								}
								if("true".equals(result)){
									break;
								}
							}
						}

			            info="update_success";
					}
				}
			}
		}
		} catch (Exception e) {
			System.out.println("NewPipPspImpl3错误异常:"+e.getMessage());
			e.printStackTrace();
		}finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return info;
	}

}
